package com.exampletest.controller;

import com.exampletest.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Value("${app.upload.path}")
    private String uploadPath;

    @Value("${app.upload.url-prefix}")
    private String urlPrefix;

    @PostMapping("/image")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 移除权限验证代码

            // 文件验证
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("请选择要上传的图片");
            }

            if (!FileUploadUtil.isImageFile(file)) {
                return ResponseEntity.badRequest().body("请上传图片文件");
            }

            if (file.getSize() > 5 * 1024 * 1024) { // 5MB
                return ResponseEntity.badRequest().body("图片大小不能超过5MB");
            }

            // 生成唯一文件名
            String originalFileName = file.getOriginalFilename();
            String fileName = FileUploadUtil.generateUniqueFileName(originalFileName);

            // 保存文件
            FileUploadUtil.saveFile(uploadPath, fileName, file);

            Map<String, String> result = new HashMap<>();
            result.put("url", urlPrefix + fileName);
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("上传文件失败");
        }
    }
}